﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace BugZillaCrawler.UI
{
    class CSVProcessor
    {
        static int _newBugCount = 0;
        public static int NewBugDownloaded
        {
            get
            {
                return _newBugCount;
            }
        }
        public static void DownloadBugList(string url, bool updateExisting)
        {
            _newBugCount = 0;
            if (string.IsNullOrEmpty(url.Trim()))
                throw new Exception("Invalid URL!");

            // Download content
            WebRequest request = HttpWebRequest.Create(url);
            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);

            // Parse content and store bug info in local storage
            bool firstLine = true;
            string lineText = string.Empty;
            while (!reader.EndOfStream)
            {
                lineText = reader.ReadLine().Replace("\"", "").Replace("\\", "");

                // Skip the first line (headers)
                if (firstLine)
                {
                    firstLine = false;
                    continue;
                }

                string[] tokens = lineText.Split((",").ToCharArray());
                int bugId = int.Parse(tokens[ColumnIndex.Id]);
                Bug bug = null;
                var existingBug = DataAccess.Database.Bugs.SingleOrDefault(b => b.Id == bugId);
                if (existingBug == null)
                {
                    _newBugCount++;
                    bug = new Bug();
                    
                    UpdateProperties(tokens, bug);
                    DataAccess.Database.Bugs.InsertOnSubmit(bug);
                    DataAccess.Database.SubmitChanges();

                    try
                    {
                        // Download descriptions
                        //Crawler.DownloadBugHistory(bugId);
                        //Crawler.DownloadBugComment(bugId);
                    }
                    catch (Exception ex)
                    {
                        // Log ex
                    }
                }
                else
                {
                    if (updateExisting)
                    {
                        UpdateProperties(tokens, existingBug);
                        DataAccess.Database.SubmitChanges();


                        try
                        {
                            // Download descriptions
                            Crawler.DownloadBugHistory(bugId);
                            Crawler.DownloadBugComment(bugId);
                        }
                        catch (Exception ex)
                        {
                            // Log ex
                        }
                    }
                }


            }
        }

        private static void UpdateProperties(string[] tokens, Bug bug)
        {
            bug.Id = int.Parse(tokens[ColumnIndex.Id]);
            bug.Severity = tokens[ColumnIndex.Severity];
            bug.Priority = tokens[ColumnIndex.Priority];
            bug.OS = tokens[ColumnIndex.OS];
            bug.AssignedTo = tokens[ColumnIndex.AssignedTo];
            bug.Status = tokens[ColumnIndex.Status];
            bug.Resolution = tokens[ColumnIndex.Resolution];
            bug.Summary = tokens[ColumnIndex.Summary];
            bug.Time = DateTime.Now;
            bug.Description = string.Empty;
            //bug.Description = Crawler.DownloadBugDescription(bug.Id);
        }

        class ColumnIndex
        {
            public static int Id = 0;
            public static int Severity = 1;
            public static int Priority = 2;
            public static int OS = 3;
            public static int AssignedTo = 4;
            public static int Status = 5;
            public static int Resolution = 6;
            public static int Summary = 7;

        }
    }
}
